Jetpack Compose 可協助您為應用程式輕鬆設計高效率的版面配置。
以下頁面詳細介紹如何設計和實作版面配置:
元素中有子項元素,就可通過測量每個子項以協助決定其大小。元素決定並回報其大小後,就有可以算出子項元素相對的位置。
在 UI 樹狀結構中完成每個節點的版面配置需要三個步驟。每個節點必須:
設計一條baseline的元件來重新計算text放的位置。
fun Modifier.firstBaselineToTop(
firstBaselineToTop: Dp
) = layout { measurable, constraints ->
// Measure the composable
val placeable = measurable.measure(constraints)
// Check the composable has a first baseline
check(placeable[FirstBaseline] != AlignmentLine.Unspecified)
val firstBaseline = placeable[FirstBaseline]
// Height of the composable with padding - first baseline
val placeableY = firstBaselineToTop.roundToPx() - firstBaseline
val height = placeable.height + placeableY
layout(placeable.width, height) {
// Where the composable gets placed
placeable.placeRelative(0, placeableY)
}
}
使用BasicLine 來計算padding
@Composable
fun Greeting(name: String,modifier: Modifier = Modifier) {
Text("Hi MyCustomBasicLine!", Modifier.firstBaselineToTop(32.dp))
}
顯示結果
使用Text預設,來計算padding
@Composable
fun Greeting(name: String,modifier: Modifier = Modifier) {
Text("Hi MyCustomBasicLine!", Modifier.padding(top = 32.dp))
}
顯示結果
使用Layout 加上 Column or Row 建立自訂版面配置
@Composable
fun MyBasicColumn(
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
Layout(
modifier = modifier,
content = content
) { measurables, constraints ->
// Don't constrain child views further, measure them with given constraints
// List of measured children
val placeables = measurables.map { measurable ->
// Measure each children
measurable.measure(constraints)
}
// Set the size of the layout as big as it can
layout(constraints.maxWidth, constraints.maxHeight) {
// Track the y co-ord we have placed children up to
var yPosition = 0
// Place children in the parent layout
placeables.forEach { placeable ->
// Position item on the screen
placeable.placeRelative(x = 0, y = yPosition)
// Record the y co-ord placed up to
yPosition += placeable.height
}
}
}
}
@Composable
fun Greeting(name: String,modifier: Modifier = Modifier) {
MyBasicColumn(modifier.padding(8.dp)) {
Text("MyCustomBasic")
Text("places items")
Text("vertically.")
Text("Custom Layout !")
}
}
顯示結果
這樣子是不是算自義的 wrap_content 呀
https://developer.android.com/jetpack/compose/layouts/custom